package hoge.memoriesalbum.get;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import hoge.memoriesalbum.R;

import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;

public class MapViewActivity extends MapActivity {

    static final String TAG = "PhotoStore";
    private static Activity mActivity;
    private static final String URI_IMAGE = "http://photo-storage.appspot.com/download?key=";

    private String mKey;
    private String mFileName;

    private Bitmap bmp = null;
    
    private MapView mapView;
    private MapController mapController;

    //Overlay
	List<Overlay> mapOverlays;
	ImageOverlay imageOverlay = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mapview);
        
        mActivity = this;

        Bundle extras = getIntent().getExtras(); 
        if (extras != null) {
        	mKey = extras.getString("key");
        	mFileName = extras.getString("filename");
        }

        mapView = (MapView)findViewById(R.id.vw_map);
        initOverlay();
		mapView.setClickable(true);
        mapView.setEnabled(true);
        mapView.invalidate();

    }

	private void initOverlay() {
		mapOverlays = mapView.getOverlays();
		imageOverlay = new ImageOverlay();
		mapOverlays.add(imageOverlay);
	}

	@Override
	protected void onResume() {
		super.onResume();
		
		new GetTask().execute();
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	
	private class GetTask extends AsyncTask<Void, Void, Boolean> {
        private ProgressDialog mProgressDialog;

        @Override
        protected void onPreExecute() {
            showPrrogressDialog();
        }

        @Override
        protected final Boolean doInBackground(Void... v) {
            // 画像取得
            bmp = getBitmap(mKey, 0);
            return true;
        }

    	protected final Bitmap getBitmap(final String key, int size) {
            Bitmap bmp = null;
            byte[] line = new byte[1024];
            int byteSize = 0;
     
            String urlStr = URI_IMAGE + key;
            
            try {
                URL url = new URL(urlStr);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("GET");
                con.connect();
                InputStream is = con.getInputStream();
                
                // バイト単位での読込
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                while ((byteSize = is.read(line)) > 0) {
                    out.write(line, 0, byteSize);
                }
     
                // オプション
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = size;
     
                byte[] byteArray = out.toByteArray();
                bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length, options);
                is.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
     
            return bmp;
        }

        @Override
        protected final void onPostExecute(Boolean flag) {
            // プログレスダイアログを閉じる
            mProgressDialog.dismiss();
            if (flag) {
//              showAlertDialog();
            	imageOverlay.setGeoPoint(mapView.getMapCenter());
            	imageOverlay.setBitmap(bmp);
            	imageOverlay.setText(mFileName);
            	mapView.postInvalidate();
            } else {
                // [todo]エラーハンドリグ
                finish();
            }
        }

        /**
         * GET中にプログレスダイアログ表示
         */
        private void showPrrogressDialog() {
            String title = getResources().getString(R.string.get_prrogress_dialog_title);
            String mes = getResources().getString(R.string.get_prrogress_dialog_mes);
            mProgressDialog = ProgressDialog.show(mActivity, title, mes, true);
        }

        /**
         * GET後に確認ダイアログ表示
         * @return
         */
        private void showAlertDialog() {
            new AlertDialog.Builder(mActivity)
            .setTitle(R.string.get_alert_dialog_title)
            .setMessage(R.string.get_alert_dialog_mes)
            .setPositiveButton(R.string.get_alert_dialog_btn, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                }
            }).create().show();
        }
	}
}
